package com.xzzz.backend.bsms.server.rbac.user;

import com.xzzz.backend.bsms.server.rbac.sys.handlelog.HandleLog;
import com.xzzz.backend.bsms.server.rbac.user.pojo.UserPageReq;
import com.xzzz.backend.bsms.server.rbac.user.pojo.UserReq;
import com.xzzz.backend.bsms.server.rbac.user.pojo.UserRes;
import com.xzzz.common.base.api.permenv.PermEnv;
import com.xzzz.common.base.pojo.PageRes;
import com.xzzz.common.base.pojo.R;
import com.xzzz.irda.auth.core.annotation.AuthIgnore;
import com.xzzz.irda.auth.core.authorization.AuthContext;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户 [User]
 *
 * @order 1
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 查询当前登录用户
     */
    @GetMapping("/current")
    public R<UserRes> current() {
        return this.user(AuthContext.getUserId());
    }

    /**
     * 全部列表
     *
     * @return 用户列表
     */
    @GetMapping("/list")
    public R<List<UserRes>> list(@ModelAttribute UserReq req) {
        return R.ok(userService.listAll(req), UserRes.class);
    }

    /**
     * 分页列表
     *
     * @return 分页结果
     */
    @GetMapping("/page")
    public R<PageRes<UserRes>> page(@ModelAttribute UserPageReq req) {
        return R.ok(userService.page(req), UserRes.class);
    }

    /**
     * 通过ID查询用户
     *
     * @param id 用户ID
     * @return 用户信息
     */
    @GetMapping("/info")
    @HandleLog(type = "user", saveParams = true)
    public R<UserRes> user(@RequestParam("id") Long id) {
        return R.ok(userService.selectById(id), UserRes.class);
    }

    /**
     * 新增或修改用户
     *
     * @param req 用户对象
     * @return 保存结果
     * @apiNote 取决于是否传入ID
     */
    @PostMapping("/save")
    public R<Long> insert(@Validated @RequestBody UserReq req) {
        if (req.getId() != null && userService.selectById(req.getId()) != null) {
            return R.ok(userService.update(req));
        } else {
            return R.ok(userService.insert(req));
        }
    }

    /**
     * 删除用户
     *
     * @param req 用户对象
     * @return 删除结果
     */
    @PostMapping("/del")
    @PermEnv(denied = {"prod", "lan"})
    public R<?> deleteById(@Validated @RequestBody UserReq req) {
        userService.delete(req.getId());
        return R.ok();
    }

    /**
     * 开发者列表
     */
    @AuthIgnore
    @GetMapping("/developers")
    public R<List<UserReq>> developers() {
        UserReq xzzz = new UserReq();
        xzzz.setNickName("小贼贼子");
        xzzz.setAvatar("https://cdn.nlark.com/yuque/0/2020/png/1875939/1609429628376-avatar/dfb7381f-8ae9-41d1-b860-2ae92113af4f.png");
        List<UserReq> users = new ArrayList<>();
        users.add(xzzz);
        return R.ok(users);
    }

}
